package cmd

import (
	"colly/config"
	"colly/pkg/initialize"
	"colly/pkg/tool"
	"context"
	"fmt"
	"github.com/Dreamacro/clash/constant"
	"github.com/fsnotify/fsnotify"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"net"
	"os"
)

var (
	Cfg        config.Config
	Log        *logrus.Logger
	Db         *gorm.DB
	runDir     string
	proxyFile  string
	configFile string
	serverName string
	currency   string
	id         int
	ctx        context.Context
)

type ClashProxyConn struct {
	NetConn net.Conn
	Proxy   constant.Proxy
}

var rootCmd = &cobra.Command{
	Use: "main",
	//Short: "Git is a distributed version control system.",
}

func getExecutableDir() (string, error) {
	// 获取当前可执行文件的路径
	exePath, err := os.Getwd()
	if err != nil {
		return "", err
	}
	return exePath, nil
}

func init() {
	rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", runDir+"/config.yaml", "clash file path")
	runDir, _ = getExecutableDir()

	if tool.CheckRunTime() {
		Log.Errorln("Run Time Error 43000")
		os.Exit(0)
	}

	loadConfig()

	Log = tool.InitLogger()

	active := Cfg.Database.Active
	db := Cfg.Database.Connection[active]
	Log.Infof("connection: %s, database: %s", active, db.Database)
	Db = initialize.NewGorm(db.Dsn(), "", "debug").Connect(ctx)
}

func loadConfig() {
	cfg := viper.New()
	cfg.SetConfigType("yaml")
	cfg.SetConfigFile(configFile)

	err := cfg.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error cfg file: %s \n", err))
	}

	err = cfg.Unmarshal(&Cfg)
	if err != nil {
		panic(fmt.Errorf("Fatal error cfg file: %s \n", err))
	}

	cfg.WatchConfig()
	cfg.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("夭寿啦~配置文件被人修改啦...")
		if err := cfg.Unmarshal(Cfg); err != nil {
			panic(fmt.Errorf("unmarshal conf failed, err:%s \n", err))
		}
	})
}

func Execute() {
	rootCmd.Execute()
}
